<template>
  <div class="login">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="phone"
          name="手机号"
          label="手机号"
          placeholder="用户名"
          :rules="[{ validator: rePhone }]"
        />
        <van-field
          v-model="code"
          name="验证码"
          label="验证码"
          placeholder="验证码"
          :rules="[{ required: true, message: '请填写验证码' }]"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              :disabled="disabled"
              @click="sendcode"
              >{{ btnmsg }}</van-button
            >
          </template>
        </van-field>
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 提交 </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { showSuccessToast } from "vant";
import md from "md5";
export default {
  data() {
    return {
      phone: "", // 手机号
      code: "", // 验证码
      btnmsg: "发送验证码",
      disabled: false, // 控制验证码是否可以点击的变量
      rePhone: (val) => {
        // val 就是输入框输入的值
        // 这是手机号的验证规则
        let re = /^1[3-9][0-9]{9}$/; // 手机号的正则
        if (!re.test(val)) {
          return "手机号格式不正确";
        }
      },
    };
  },
  created() {},
  methods: {
    onSubmit() {
      // jwt
      // 点击提交触发的函数
      showSuccessToast("登录成功！");
      let txt = "666888";
      this.$store.commit("saveToken", md(txt));
      this.$router.back();
    },
    sendcode() {
      // 发送验证码
      this.disabled = true; // 按钮不可以点击
      let num = 60;
      let clearTime = setInterval(() => {
        num--;
        this.btnmsg = `${num}s后发送`;
        if (num == 0) {
          clearInterval(clearTime);
          this.btnmsg = "发送验证码";
          this.disabled = false;
        }
      }, 1000);
    },
  },
  components: {},
};
</script>

<style lang="scss" scoped>
.login {
  height: 100%;
  overflow: hidden;
  background-image: linear-gradient(to bottom right, red, yellow);
  .van-form {
    margin-top: 200px;
  }
}
</style>
